package com.jorado.apollo.service;

import com.ctrip.framework.apollo.core.ConfigConsts;
import com.google.common.base.Strings;
import com.jorado.apollo.dto.ItemDTO;
import com.jorado.apollo.model.NamespaceTextModel;
import org.apache.http.impl.client.CloseableHttpClient;

public class ItemApiService extends AbstractApiService {

    public ItemApiService(CloseableHttpClient client, String baseUrl) {
        super(client, baseUrl);
    }

    public void createItem(String appId, String env,
                           String clusterName, String namespaceName,
                           ItemDTO itemDTO) {

        if (Strings.isNullOrEmpty(clusterName)) {
            clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
        }

        checkNotEmpty(appId, "App id");
        checkNotEmpty(env, "Env");

        String path = String.format("apps/%s/envs/%s/clusters/%s/namespaces/%s/item", escapePath(appId), escapePath(env), escapePath(clusterName), escapePath(namespaceName));

        try {
            post(path, itemDTO);
        } catch (Throwable ex) {
            throw new RuntimeException(String
                    .format("create item for appId: %s, cluster: %s, namespace: %s, item:%s in env: %s failed", appId, clusterName,
                            namespaceName, itemDTO, env), ex);
        }
    }

    public void updateItems(String appId, String env,
                            String clusterName, String namespaceName,
                            NamespaceTextModel model) {

        if (Strings.isNullOrEmpty(clusterName)) {
            clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
        }

        checkNotEmpty(appId, "App id");
        checkNotEmpty(env, "Env");

        String path = String.format("apps/%s/envs/%s/clusters/%s/namespaces/%s/items", escapePath(appId), escapePath(env), escapePath(clusterName), escapePath(namespaceName));

        try {
            put(path, model);
        } catch (Throwable ex) {
            throw new RuntimeException(String
                    .format("update items by text for appId: %s, cluster: %s, namespace: %s, items:%s in env: %s failed", appId, clusterName,
                            namespaceName, model, env), ex);
        }
    }
}
